<!-- 添加 联代/竞品 -->
<template>
  <div class="proxies_match">
    <dt-modal-edit
      ref="edit"
      :title="info.title"
      :label-width="130"
      okText="保存"
      :width="60"
      @ok="onOk"
      @cancelData="cancelData">
      <Row class="label_warp">
        <Col span="24" class="tips">
          <Icon type="md-alert" class="tips_icon" />
          <div>{{ info.topTips }}</div>
        </Col>
      </Row>
      <div class="addOptions">
        <Checkbox v-model="checkInfo.info1" :disabled="lastOne && checkInfo.info1" @on-change="checkChange">
          线索
        </Checkbox>
        <Checkbox v-model="checkInfo.info2" :disabled="lastOne && checkInfo.info2" @on-change="checkChange">
          来人
        </Checkbox>
        <Checkbox v-model="checkInfo.info3" :disabled="lastOne && checkInfo.info3" @on-change="checkChange">
          成交
        </Checkbox>
      </div>

      <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="100">
        <div class="proxies_match_form">
          <div class="proxies_match_gun" ref="formValidategun">
            <div class="proxies_match_form_box" v-for="(item, index) in formValidate.list" :key="index">
              <div class="addData">
                <Row>
                  <Col span="16">
                    <FormItem
                      :label="`${labelTxt}名称：`"
                      :prop="`list.${index}.generationName`"
                      :rules="ruleValidate.generationName"
                      class="house_search">
                      <Input
                        type="text"
                        :placeholder="`请输入${labelTxt}名称`"
                        v-model="item.generationName"
                        maxlength="20"
                        :disabled="item.disabledFlag"
                        @on-blur="onBlur(item, index)"
                        @on-focus="onFocus(item, index)" />
                    </FormItem>
                  </Col>
                  <Col span="4">
                    <div class="edit_btn">
                      <span v-if="item.disabledFlag" @click="addBtnEdit(index)">编辑</span>
                      <span @click="addBtnDel(item, index)">删除</span>
                    </div>
                  </Col>
                </Row>

                <Row v-if="info.type == '1'">
                  <Col span="16">
                    <FormItem
                      :label="`联代类型：`"
                      :prop="`list.${index}.cooperationModeType`"
                      :rules="ruleValidate.cooperationModeType"
                      class="house_search">
                      <RadioGroup v-model="item.cooperationModeType">
                        <Radio :label="1">甲方联代</Radio>
                        <Radio :label="2">乙方联代</Radio>
                      </RadioGroup>
                    </FormItem>
                  </Col>
                </Row>

                <Row>
                  <Col span="6" v-if="checkInfo.info1">
                    <FormItem :label="`${labelTxt}线索：`" :prop="`list.${index}.clueCount`">
                      <InputNumber
                        v-model="item.clueCount"
                        :min="0"
                        :precision="0"
                        @on-blur="changeInput(item, index, 'clueCount')"
                        @on-focus="focusNum(item, index, 'clueCount')" />
                    </FormItem>
                  </Col>
                  <Col v-if="checkInfo.info1" span="1" class="unit">组</Col>
                  <Col span="6" v-if="checkInfo.info2">
                    <FormItem :label="`${labelTxt}来人：`" :prop="`list.${index}.arrivePeople`">
                      <InputNumber
                        v-model="item.arrivePeople"
                        :min="0"
                        :precision="0"
                        @on-blur="changeInput(item, index, 'arrivePeople')"
                        @on-focus="focusNum(item, index, 'arrivePeople')" />
                    </FormItem>
                  </Col>
                  <Col v-if="checkInfo.info2" span="1" class="unit">组</Col>
                  <Col span="6" v-if="checkInfo.info3">
                    <FormItem :label="`${labelTxt}成交：`" :prop="`list.${index}.clinchDeal`">
                      <InputNumber
                        v-model="item.clinchDeal"
                        :min="0"
                        :precision="0"
                        @on-blur="changeInput(item, index, 'clinchDeal')"
                        @on-focus="focusNum(item, index, 'clinchDeal')" />
                    </FormItem>
                  </Col>
                  <Col v-if="checkInfo.info3" span="1" class="unit">套</Col>
                </Row>
              </div>
            </div>
          </div>
          <div class="add_btn">
            <Icon type="md-add-circle" />
            <span @click="creatAdd">添加1个{{ labelTxt }}</span>
          </div>
        </div>
      </Form>
    </dt-modal-edit>
    <add-history ref="addHistory" @success="onSuccess" />
  </div>
</template>

<script>
  import dailyApi from '@/biz/buildingHome/daily'
  import addHistory from './addHistory.vue'
  export default {
    components: { addHistory },
    data() {
      return {
        checkInfo: {
          info1: false,
          info2: true,
          info3: true
        },

        findDailyGenerationAllocationData: null,
        info: {},
        labelTxt: '',
        formValidate: {
          list: []
        },
        ruleValidate: {
          generationName: [{ required: true, message: `请输入名称`, trigger: 'blur' }],
          cooperationModeType: [
            { required: true, type: 'number', message: `请选择联代类型`, trigger: 'change' }
          ]
        },
        historyFlag: true,
        oldName: '',
        historyLen: 0,
        historyList: [],
        lastOne: false
      }
    },
    methods: {
      updateTask() {
        let params = {
          taskId: 35,
          buildingId: this.$dt.buildInfo().housesId,
          date: this.info.currentDate,
          taskStatus: 2
        }
        dailyApi.updateTask(params).then((res) => {
          console.log('完成')
        })
      },
      checkChange(val) {
        console.log(val, 'vvv')
        const trueCount = Object.values(this.checkInfo).filter((value) => value).length
        if (trueCount === 1) {
          this.lastOne = true
        } else {
          this.lastOne = false
        }
      },
      onFocus(data) {
        console.log(data.generationName)
        this.oldName = data.generationName
      },
      onBlur(data, idx) {
        console.log(this.oldName, 'oldName', data)
        // if (this.oldName != data.generationName) {
        //改变调用判断名称重复接口
        console.log(this.oldName, '++++', data.generationName)
        // let allList = [...this.formValidate.list, ...this.historyList]
        this.formValidate.list.forEach((item, index) => {
          if (index != idx) {
            if (item.generationName == data.generationName) {
              this.$Message.warning(`已存在${data.generationName}${this.labelTxt}名称，请重新填写`)
              data.repetition_Flag = true
              item.repetition_Flag = true
              this.formValidate.list.splice(idx, 1, data)
              this.formValidate.list.splice(index, 1, item)
            } else {
              data.repetition_Flag = false
              item.repetition_Flag = false
              this.formValidate.list.splice(idx, 1, data)
              this.formValidate.list.splice(index, 1, item)
            }
          }
        })
        this.historyList.forEach((item, index) => {
          if (index != idx) {
            if (item.generationName == data.generationName) {
              this.$Message.warning(
                `已在历史数据中存在${data.generationName}${this.labelTxt}名称，请重新填写`
              )
              data.repetition_Flag = true
              this.formValidate.list.splice(idx, 1, data)
            } else {
              data.repetition_Flag = false
              this.formValidate.list.splice(idx, 1, data)
            }
          }
        })
        // }
      },

      findDailyGenerationAllocation() {
        let params = {
          buildingId: this.$dt.buildInfo().housesId,
          date: this.info.currentDate,
          projectType: this.info.type
        }
        dailyApi.findDailyGenerationAllocation(params).then((res) => {
          console.log(res, 'vvv')
          if (res) {
            this.findDailyGenerationAllocationData = res
            this.checkInfo.info1 = Boolean(res.clueStatus)
            this.checkInfo.info2 = Boolean(res.arrivePeopleStatus)
            this.checkInfo.info3 = Boolean(res.clinchDealStatus)
            this.checkChange()
          }
        })
      },
      show(data) {
        this.info = data
        this.labelTxt = data.type == 1 ? '联代' : '竞品'
        this.$refs.edit.show()
        this.getData()
        let refGun = this.$refs.formValidategun
        refGun.scrollTop = 0

        this.findDailyGenerationAllocation()
      },
      getData() {
        let params = {
          buildingId: this.$dt.buildInfo().housesId,
          projectType: this.info.type,
          date: this.info.currentDate
        }
        dailyApi.findDailyGenerationList(params).then((res) => {
          console.log(res, '3333')
          if (res.length == 0) {
            this.formValidate.list = [
              {
                generationName: '',
                arrivePeople: 0,
                clinchDeal: 0
              }
            ]
          } else {
            this.formValidate.list = res
          }
          this.getHistoryData(this.formValidate.list)
        })
      },
      getHistoryData(list) {
        let ids = []
        list.forEach((item) => {
          if (item.generationId) ids.push(item.generationId)
        })
        let dataChildren = {
          ids,
          date: this.info.currentDate,
          type: this.info.type
        }
        this.$refs.addHistory.getData(dataChildren).then((res) => {
          console.log(res)
          this.historyList = res
          this.historyLen = res ? res.length : 0
        })
      },
      //编辑
      addBtnEdit(index) {
        console.log(index)
        this.formValidate.list[index].disabledFlag = false
        this.formValidate.list = JSON.parse(JSON.stringify(this.formValidate.list))
        console.log(this.formValidate.list)
      },
      //删除
      addBtnDel(item, index) {
        console.log(item)
        if (item.generationId) {
          this.$Modal.confirm({
            title: `“${this.labelTxt}”删除确认`,
            content: `请确认，是否将“${item.generationName}”从“PK数据”中删除？删除后，“${item.generationName}”将不在今日“案场日报”中显示`,
            closable: true,
            onOk: () => {
              this.formValidate.list.splice(index, 1)
              let params = {
                dailyGenerationId: item.generationId,
                id: item.id
              }
              dailyApi.deleteDailyGenerationById(params).then((res) => {
                this.$Message.success('删除成功')
              })
              this.getHistoryData(this.formValidate.list)
            },
            onCancel: () => {}
          })
        } else {
          this.formValidate.list.splice(index, 1)
        }
      },
      //新增
      creatAdd() {
        let ids = []
        this.formValidate.list.forEach((item) => {
          if (item.generationId) ids.push(item.generationId)
        })
        let dataChildren = {
          ids,
          date: this.info.currentDate,
          type: this.info.type
        }
        this.$refs.addHistory.getData(dataChildren).then((res) => {
          this.historyList = res
          this.historyLen = res ? res.length : 0
          if (res.length > 0) {
            let data = {
              labelTxt: `${this.labelTxt}`,
              topTips: `以下为您已添加但未在日报中显示的${this.labelTxt}，您可重新添加至日报已避免重复`,
              ids
            }
            this.$refs.addHistory.show(data)
          } else {
            let obj = {
              generationName: '',
              arrivePeople: 0,
              clinchDeal: 0,
              disabledFlag: false
            }
            this.$set(this.formValidate.list, this.formValidate.list.length, obj)
          }
        })
      },
      //历史添加 选择返回
      onSuccess(data) {
        this.$set(this.formValidate.list, this.formValidate.list.length, data)
        this.getHistoryData(this.formValidate.list)
        console.log(this.$refs.formValidategun)
        this.$nextTick(() => {
          let refGun = this.$refs.formValidategun
          let refGunSH = refGun.scrollHeight
          refGun.scrollTop = refGunSH
        })
      },
      changeInput(item, index, key) {
        console.log(item[key])
        if (!item[key]) {
          this.formValidate.list[index][key] = 0
          this.formValidate.list = JSON.parse(JSON.stringify(this.formValidate.list))
        }
      },
      focusNum(item, index, key) {
        console.log(item[key])
        if (item[key] == 0) {
          this.formValidate.list[index][key] = null
          this.formValidate.list = JSON.parse(JSON.stringify(this.formValidate.list))
        }
      },
      cancelData() {
        this.$emit('success')
        this.$refs.formValidate.resetFields()
      },
      onOk() {
        this.$refs.formValidate.validate((valid) => {
          if (valid) {
            console.log(this.formValidate.list, 'this.formValidate.list')
            let updateFlag = true
            this.formValidate.list.forEach((item) => {
              item.buildingId = this.$dt.buildInfo().housesId
              item.createDate = this.info.currentDate
              if (item.repetition_Flag) {
                updateFlag = false
                this.$Message.warning(`${this.labelTxt}名称:"${item.generationName}"存在重复`)
                return false
              }
            })

            let dailyGenerationTitleReq = {
              arrivePeopleStatus: this.checkInfo.info2 ? 1 : 0,
              buildingId: this.$dt.buildInfo().housesId,
              clinchDealStatus: this.checkInfo.info3 ? 1 : 0,
              clueStatus: this.checkInfo.info1 ? 1 : 0,
              id: this.findDailyGenerationAllocationData.id,
              projectType: this.info.type
            }

            if (updateFlag) {
              let params = {
                buildingId: this.$dt.buildInfo().housesId,
                dailyGenerationDataReqList: this.formValidate.list,
                projectType: this.info.type,
                createDate: this.info.currentDate,
                dailyGenerationTitleReq: dailyGenerationTitleReq
              }
              console.log(params, '提交数据')

              dailyApi.updateDailyGeneration(params).then((res) => {
                // this.$emit('success')
                this.$Message.success('保存成功')
                this.updateTask()
                this.cancelData()
                this.$refs.edit.hide()
              })
            }
          }
        })
      }
    }
  }
</script>
<style lang="scss" scoped>
  .proxies_match {
    .label_warp {
      background-color: rgba(254, 252, 236, 1);
      width: auto;
      line-height: 32px;
      padding: 10px;

      .tips {
        line-height: 20px;
        font-size: 14px;
        display: flex;
        justify-content: center;

        .tips_icon {
          font-size: 20px;
          color: #0f42a7;
          vertical-align: sub;
        }
      }
    }
    .addOptions {
      padding: 20px 0 0 20px;
    }

    .proxies_match_form {
      .proxies_match_gun {
        max-height: 400px;
        overflow-x: hidden;
        overflow-y: auto;

        .proxies_match_form_box {
          padding-top: 30px;
          border-top: 1px #ccc dashed;
          display: flex;
          flex-direction: row;

          .addData {
            flex: 1;
          }

          .edit_btn {
            color: #2b85e4;
            width: 140px;
            padding-left: 20px;
            cursor: pointer;

            span {
              display: inline-block;
              padding: 0 5px;
              line-height: 34px;
            }
          }
        }

        .proxies_match_form_box:nth-child(1) {
          border: none;
        }
      }

      .add_btn {
        color: #2b85e4;
        font-weight: normal;
        font-size: 14px;
        cursor: pointer;
        padding: 10px 0;
      }

      .unit {
        margin: 5px;
      }
    }
  }
</style>
